# -*- coding: utf-8 -*- 
# @Time    : 2021/3/24
# @Author  : WangHong 
# @FileName: train.py
# @Software: PyCharm
from tensorflow import keras
from data_preprocessing import get_data

maxlen = 200
max_words = 10000
embedding_dim = 100

model = keras.models.Sequential([
    keras.layers.Embedding(max_words, embedding_dim, input_length=maxlen),
    keras.layers.LSTM(128, recurrent_dropout=0.25),
    keras.layers.Dropout(0.25),
    keras.layers.Dense(3, activation='softmax')
])
model.summary()

model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

x_train, y_train, x_test, y_teat = get_data()

print("#####################数据预处理完成，开始模型训练#####################")

# 训练模型
history = model.fit(x_train, y_train,
                    epochs=10,
                    batch_size=128,
                    validation_data=(x_test, y_teat))

# 损失函数和准确率可视化
import matplotlib.pyplot as plt

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(1, len(acc) + 1)

plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()

plt.figure()

plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()
